package com.hs.core.setup;

import java.sql.Connection;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;

import com.hs.Environment;
import com.hs.core.db.DatabaseConnection;
import com.hs.log.HsLogger;

public class SetupDatabase {
	private static final HsLogger logger = HsLogger.getLogger(SetupDatabase.class.getName());
	protected static final String SQL_PROPERTY_TABLE = "tables.properties";
	protected static final String SQL_PROPERTY_SEQ = "seq.properties";
	private static String CONNECTION_VALIDATION_QUERY = null;
	private static String EXISTENCE_VALIDATION_QUERY = null;
	private static Properties props  = new Properties();
	private static Properties seqprops  = new Properties();
	
	public SetupDatabase(){
		props = Environment.loadProperties(SQL_PROPERTY_TABLE);
		seqprops = Environment.loadProperties(SQL_PROPERTY_SEQ);
		this.init(props);
	}
	
	protected void init(Properties props) {
		 
	}
	/**
	 *
	 */
	public void createTables(Connection conn) {
		// note that this method is called during creation failures, so be careful to
		// catch errors that might result from a partial failure during install.  also
		// note that the coding style violation here is intentional since it makes the
		// actual work of the method more obvious.
		try {
			if(null != props){
				Set entrys =  props.entrySet();
			    Iterator iter = entrys.iterator();
			   
			    while(iter.hasNext()){
			    	Entry entry = (Entry)iter.next();
			    	String key = entry.getKey()+"";
			    	String value = entry.getValue()+"";
			    	logger.fine("create table " + key + value); 
			    	System.out.println("create table " + key + value); 
			    	DatabaseConnection.executeUpdate(value, conn);
			    }
			}
			if(null != seqprops){
				Set entryseq =  seqprops.entrySet();
			    Iterator iterseq = entryseq.iterator();
			   
			    while(iterseq.hasNext()){
			    	Entry entry = (Entry)iterseq.next();
			    	String key = entry.getKey()+"";
			    	String value = entry.getValue()+"";
			    	logger.fine("create seq " + key + value); 
			    	DatabaseConnection.executeUpdate(value, conn);
			    }
			}
			
		} catch (Exception e) { e.printStackTrace();;
		 }
		 
	}
	public static String connectionValidationQuery() {
		return "SELECT 1";
	}
	/**
	 * Return a simple query, that if successfully run indicates that JAMWiki
	 * tables have been initialized in the database.
	 *
	 * @return Returns a simple query that, if successfully run, indicates
	 *  that JAMWiki tables have been set up in the database.
	 */
	public static String existenceValidationQuery() {
		return "SELECT * FROM APP.HS_GROUPINFO" ;
	}
	public void dropTables(Connection conn) throws Exception {
//		DatabaseConnection.executeUpdate(STATEMENT_CREATE_VIRTUAL_WIKI_TABLE, conn);
//		DatabaseConnection.executeUpdate(STATEMENT_CREATE_WIKI_USER_TABLE, conn);
//		DatabaseConnection.executeUpdate(STATEMENT_CREATE_WIKI_USER_INFO_TABLE, conn);
//		DatabaseConnection.executeUpdate(STATEMENT_CREATE_WIKI_USER_LOGIN_INDEX, conn);
//		DatabaseConnection.executeUpdate(STATEMENT_CREATE_TOPIC_TABLE, conn);
//		DatabaseConnection.executeUpdate(STATEMENT_CREATE_TOPIC_VERSION_TABLE, conn);
//		DatabaseConnection.executeUpdate(STATEMENT_CREATE_TOPIC_CURRENT_VERSION_CONSTRAINT, conn);
//		DatabaseConnection.executeUpdate(STATEMENT_CREATE_WIKI_FILE_TABLE, conn);
//		DatabaseConnection.executeUpdate(STATEMENT_CREATE_WIKI_FILE_VERSION_TABLE, conn);
//		DatabaseConnection.executeUpdate(STATEMENT_CREATE_CATEGORY_TABLE, conn);
//		DatabaseConnection.executeUpdate(STATEMENT_CREATE_GROUP_TABLE, conn);
//		DatabaseConnection.executeUpdate(STATEMENT_CREATE_ROLE_TABLE, conn);
//		DatabaseConnection.executeUpdate(STATEMENT_CREATE_ROLE_MAP_TABLE, conn);
//		DatabaseConnection.executeUpdate(STATEMENT_CREATE_RECENT_CHANGE_TABLE, conn);
//		DatabaseConnection.executeUpdate(STATEMENT_CREATE_WATCHLIST_TABLE, conn);
	}
	/**
	 *
	 */
	public static String getConnectionValidationQuery() {
		return (!StringUtils.isBlank(CONNECTION_VALIDATION_QUERY)) ? CONNECTION_VALIDATION_QUERY : null;
	}

	/**
	 *
	 */
	public static String getExistenceValidationQuery() {
		return (!StringUtils.isBlank(EXISTENCE_VALIDATION_QUERY)) ? EXISTENCE_VALIDATION_QUERY : null;
	}

	/**
	 *
	 */
	public synchronized  void initialize() {
		try {
			CONNECTION_VALIDATION_QUERY = connectionValidationQuery();
			EXISTENCE_VALIDATION_QUERY = existenceValidationQuery();
			// initialize connection pool in its own try-catch to avoid an error
			// causing property values not to be saved.
			// this clears out any existing connection pool, so that a new one will be created on first access
			DatabaseConnection.closeConnectionPool();
		} catch (Exception e) {
			logger.severe("Unable to initialize database", e);
		}
	}

	public synchronized  void shutdown() {
		try {
			DatabaseConnection.closeConnectionPool();
		} catch (Exception e) {
			logger.severe("Unable to close the connection pool on shutdown", e);
		}
	}
}
